﻿using Bookify.Application.Abstractions.Authentication;
using Bookify.Application.Abstractions.Data;
using Bookify.Application.Abstractions.Messaging;
using Bookify.Domain.Abstractions;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bookify.Application.Users.GetLoggedInUser
{
    internal sealed class GetLoggedInUserQueryHandler
        : IQueryHandler<GetLoggedInUserQuery, UserResponse>
    {
        private readonly ISqlConnectionFactory _sqlConnectionFactory;
        private readonly IUserContext _userContext;

        public GetLoggedInUserQueryHandler(ISqlConnectionFactory sqlConnectionFactory, IUserContext userContext)
        {
            _sqlConnectionFactory = sqlConnectionFactory;
            _userContext = userContext;
        }
        public async Task<Result<UserResponse>> Handle(
            GetLoggedInUserQuery request, 
            CancellationToken cancellationToken)
        {
            using var connect = _sqlConnectionFactory.CreateConnection();
            
            const string sql = """
                SELECT
                    id AS Id,
                    email AS Email,
                    first_name AS FirstName,
                    last_name AS LastName
                FROM users
                WHERE identity_id = @IdentityId
                """;
            
            var user = await connect.QuerySingleAsync<UserResponse>(
                sql, 
                new { IdentityId = _userContext.IdentityId });

            return user;            
        }

    }
}
